﻿@{
    ViewBag.Title = "Product";
    Layout = null;
}



<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>数据表格</title>
    <link href="//unpkg.com/layui@2.9.16/dist/css/layui.css" rel="stylesheet">
  @*   <link rel="stylesheet" href="https://www.layui.com/layui/css/layui.css">
    <script src="https://www.layui.com/layui/layui.js"></script> *@

</head>
<body>
    <div class="layui-container">
        <div class="layui-row">
            <div class="layui-col-md3">
                <div class="layui-form-item" width="50%">
                    <input type="text" placeholder="请输入分类名称" class="layui-input">
                </div >
                <body>
                    <div id="test" class="demo-tree"></div>
                </body>

            </div>
            <div class="layui-col-md9">
                <div class="layui-form-item">
                    <div class="layui-input-inline">
                        <input type="text" placeholder="物料编码" id="ProductCode" name="ProductCode" class="layui-input">
                    </div>
                    <div class="layui-input-inline">
                        <input type="text" placeholder="物料名称" id="ProductName" name="ProductName" class="layui-input">
                    </div>
                    <button class="layui-btn" id="btnSearch">搜索</button>


                    <button id="openPopup" class="layui-btn">添加</button>
                    <button id="editPopup" type="button" class="layui-btn layui-bg-orange">编辑</button>
                    <button type="button" class="layui-btn layui-bg-red" >删除</button>
                    <table class="layui-hide" id="demo" lay-filter="test">
                    </table>
            

                    <script type="text/html" id="barDemo">

                        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
                    </script>
                </div>
            </div>
          </div>
    </div>
    

    <script src="~/libs/jquery/jquery.js"></script>
    <script src="//unpkg.com/layui@2.9.16/dist/layui.js"></script>
    <script>
        layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider'], function () {
            var layer = layui.layer //弹层
                , table = layui.table //表格
            var form = layui.form;
            var tree = layui.tree;
            
          

            // 可在此初始化组件和操作dom
            querylist = function () {

              var  ProductName=$('#ProductName').val()
              var  ProductCode= $('#ProductCode').val()
                //执行一个 table 实例
                table.render({
                    elem: '#demo'
                    , height: 520
                    , url: '/Wyx/GetProductList'  //数据接口
                    ,where:
                    {
                        ProductName: ProductName,
                        ProductCode: ProductCode
                    }
                   
                  
                    //, toolbar: 'default' //开启头工具栏，此处显示默认图标，可以自定义模板，详见文档
                    , page: {
                        limit: 3,
                        limits: [3, 6, 9, 12],
                        prev: '上一页',
                        next: '下一页',
                        first: '首页',
                        last: '尾页'
                    },
                    request: {
                        pageName: 'pageIndex', //页码的参数名称，默认：page
                        limitName: 'pageSize' //每页数据量的参数名，默认：limit
                    },
                    parseData:function(res){
                        return {
                            "code": res.code, //解析接口状态
                           
                            "count": res.count, //解析数据长度
                            "data": res.data //解析数据列表
                        };
                    },
                    method: 'get', //默认：get请求
                     cols: [[ //表头
                          { type: 'checkbox', fixed: 'left' }//锁定第一列
                        , { field: 'ProductCode', title: '物料编码', width: 80 }
                        , { field: 'ProductName', title: '物料名称', width: 80 }
                        , { field: 'SpecifiCation', title: '规格型号', width: 80 }
                        , { field: 'UnitName', title: '单位', width: 80 }
                        // , { field: 'ProductTypeId', title: '物料/产品', width: 80 }
                        , { field: 'ProductItem', title: '所属分类', width: 80 }
                        , {
                            field: 'IsEnable', title: '是否启用', width: 80, sort:true, templet: function (row) {
                                return row.IsEnable == true ? "是" : "否";
                            
                            }
                        }
                        , {
                            field: 'IsStock', title: '是否启用', width: 80, sort: true, templet: function (row) {
                                var tmp = row.IsStock == true ? "是" : "否";
                                return tmp;
                            }
                        }
                        // , { field: 'CreationTime', title: '创建时间', width: 90 }
                        , { fixed: 'right', width: 165, align: 'center', toolbar: '#barDemo' }

                    ]],
                  
                  
                    done: function () {
                        //表格绑定数据后的回调函数
                        layer.msg('权限展示完成！', {
                            icon: 1,
                            time: 1000
                        });
                    }

                                     
                
                });
            }
          

            querylist();
            $("#btnSearch").on("click", function () {
                querylist();
            })


            //监听 表行 工具栏事件
            table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    , layEvent = obj.event; //获得 lay-event 对应的值
              
                if (layEvent === 'delete') {
                    layer.confirm('真的删除行么', function (index) {
                        $.ajax({

                            url: "/Wyx/DeleteProductData?id=" + data.Id,
                            type: "GET",
                        });
                       
                        obj.del(); //删除对应行（tr）的DOM结构
                        layer.close(index);
                        //向服务端发送删除指令
                    });
                } else if (layEvent === 'edit') {

                    layer.open({
                        title: '修改',
                        type: 2,
                        anim: 1,
                        offset: 't',
                        area: ['50%', '70%'],
                        content: `/Wyx/Productupdate?id=${data.Id}`,
                        
                        end: function () {
                            querylist()
                        }
                    });
                    console.log(data.Id),
                    sessionStorage.setItem("id", data.Id);
                  
                 
                }

            });




            layui.use(['tree', 'jquery'], function () {
                var tree = layui.tree;
                var $ = layui.jquery;

                // 动态获取数据的函数（模拟 AJAX 请求）
                function fetchData(callback) {
                    $.ajax({
                        url: 'https://localhost:44311/GetProductType?parentId=0', // 替换为你的 API 地址
                        method: 'GET',
                        success: function (res) {
                            // 将数据转换为树形控件所需的格式
                            var formattedData = formatData(res);
                            callback(formattedData);
                            console.log('数据格式化完成:', formattedData);
                        },
                        error: function (err) {
                            console.error('数据请求失败:', err);
                        }
                    });
                }

                // 格式化数据
                function formatData(data) {
                    return data.map(item => ({
                        title: item.label,
                        id: item.value,
                        children: formatData(item.children || [])
                    }));
                }

                // 初始化树形控件
                fetchData(function (data) {
                    tree.render({
                        elem: '#test',
                        data: data,
                        // 点击事件
                        onclick: function (obj) {
                            console.log('当前点击的节点:', obj.data);
                        }
                    });
                });
            });



            document.getElementById('openPopup').onclick = function () {
                layui.use(['layer', 'form'], function () {
                    var layer = layui.layer;
                    var form = layui.form;

                    function createModalContent() {
                        return `
                        <div class="layui-form" style="padding: 20px;">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">* 物料编码</label>
                                    <div class="layui-input-inline">
           <input type="text" name="productcode" id="productcode" lay-verify="required" placeholder="请输入物料编码" autocomplete="off" class="layui-input">
                                    </div>
                                  
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">* 物料名称</label>
                                    <div class="layui-input-inline">
                             <input type="text" name="productname" id="productname" lay-verify="required" placeholder="请输入物料名称" autocomplete="off" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">规格型号</label>
                                <div class="layui-input-block">
                                <input type="text" name="specification" id="specification" placeholder="请输入规格型号" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">* 单位</label>
                                    <div class="layui-input-inline">
                                                                <select name="unitname" id="unitname" lay-verify="required">
                                            <option value="">请选择单位</option>
                                            <option value="kg">千克</option>
                                            <option value="g">克</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">* 物料/产品分类</label>

                                    <div id="productitem" name="productitem"  class="demo-tree"></div>
                                                             <input type="hidden" name="productTypeId" id="productTypeId">
                                                     <input type="hidden" name="productItem" id="productItem">
                                        </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">是否启用</label>
                                <div class="layui-input-block">
                                                    <input type="radio" id="isenable" name="isenable" value="true" title="是" checked>
                                                    <input type="radio" id="isenable" name="isenable" value="false" title="否">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">安全库存</label>
                                <div class="layui-input-block">
                                                                            <input type="radio" id="isstock" name="isstock" value="true" title="是">
                                                                            <input type="radio" id="isstock" name="isstock" value="false" title="否" checked>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">备注</label>
                                <div class="layui-input-block">
                                                            <input type="text" name="remark" id="remark" placeholder="请输入内容" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                            <button class="layui-btn" type="submit" lay-submit lay-filter="btnAdd" >确定</button>
                                    <button type="button" class="layui-btn layui-btn-primary" onclick="closeModal()">取消</button>
                                </div>
                            </div>
                        </div>`;
                    }


                    

                    layui.use(['form', 'jquery', 'element'], function () {
                        var form = layui.form,
                            $ = layui.jquery;
                        $ = layui.$;
                        // 监听确认按钮点击事件
                        form.on('submit(btnAdd)', function (data) {
                            // 获取表单数据
                            console.log(data);
                            // 发送 AJAX 请求
                            $.ajax({
                                url: "/Wyx/AddProductData",
                                type: "get",
                                data: data.field,
                                // 将数据转换为JSON字符串
                                dataType: "json",
                                success: function (res) {
                                    if (res) {
                                        console.log(res);
                                        layer.msg('保存成功', {
                                            icon: 1,
                                            time: 1000
                                        }, function () {

                                        });

                                        var index = parent.layer.getFrameIndex(window.name);
                                        parent.layer.close(index);

                                    }


                                }
                            });
                        });



                    });
                 


                    layui.use(['tree', 'jquery'], function () {
                        var tree = layui.tree;
                        var $ = layui.jquery;

                        function fetchData(callback) {
                            $.ajax({
                                url: 'https://localhost:44311/GetProductType?parentId=0', // 替换为你的 API 地址
                                method: 'GET',
                                success: function (res) {
                                    // 将数据转换为树形控件所需的格式
                                    var formattedData = formatData(res);
                                    callback(formattedData);
                                    console.log('数据格式化完成:', formattedData);
                                },
                                error: function (err) {
                                    console.error('数据请求失败:', err);
                                }
                            });
                        }


                        // 格式化数据
                        function formatData(data) {
                            return data.map(item => ({
                                title: item.label,
                                id: item.value,
                                children: formatData(item.children || [])
                            }));
                        }



                        fetchData(function (data) {
                            tree.render({
                                elem: '#productitem', // 这里的 #productitem 是树形控件展示的地方
                                data: data,
                                onlyIconControl: true,
                                // 点击事件
                                click: function (obj) {
                                    console.log('当前点击的节点:', obj.data);
                                    // 确认这里获取到的obj.data有title属性
                                    if (obj.data && obj.data.title) {
                                        // 将选中的节点值设置到物料/产品输入框
                                        $('#productTypeId').val(obj.data.id); // 设置输入框的值为节点文本
                                        $('#productItem').val(obj.data.title); // 设置输入框的值为节点文本
                                        console.log('设置物料/产品分类成功:', obj.data.title);
                                    } else {
                                        console.warn('点击的节点没有title属性');
                                    }
                                }
                            });
                        });
                    });




                    function loadSelectOptions() {
                        // 加载单位选项
                        fetch('/api/units') // 替换为你的API地址
                            .then(response => response.json())
                            .then(data => {
                                var unitSelect = document.getElementById('unitSelect');
                                unitSelect.innerHTML = '<option value="">请选择单位</option>'; // 清空之前的选项
                                data.forEach(unit => {
                                    unitSelect.innerHTML += `<option value="${unit.value}">${unit.label}</option>`;
                                });
                                form.render('select'); // 更新layui表单
                            }); fetch('/api/units') // 替换为你的API地址
                    }


                    layer.open({
                        type: 1,
                        title: '新增物料/产品',
                        area: ['800px', '500px'],

                        content: createModalContent(),
                        success: function (layero, index) {
                            var date = new Date();
                            var year = date.getFullYear();
                            var month = ('0' + (date.getMonth() + 1)).slice(-2);
                            var day = ('0' + date.getDate()).slice(-2);
                            var randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');

                            var productCode = year + month + day + randomNum;

                            document.getElementById('productcode').value = productCode;
                            form.render(); // 渲染表单
                        },
                        yes: function (index, layero) {
                            var formData = layero.find('.layui-form').serializeArray();
                            layer.msg('你点击了确定按钮！');
                            console.log(formData);
                            layer.close(index);
                        },
                        btn2: function (index, layero) {
                            layer.msg('你点击了取消按钮！');
                            layer.close(index);
                        }
                    });
                });
            };

     

      



                

<<<<<<< HEAD
                    // 假设 existingData 是你从数据库获取的需要反填的数据
                    var existingData = {
                        productcode:"",
                        productname: '',
                        SpecifiCation: '',
                        unitname: '',
                        productItem: '',
                        isenable: "",
                        isstock: "",
                        remark: '',
                        autoGenerate: false
                    };

                 

                    function openEditModal(existingData) {
                        layui.use(['layer', 'form'], function () {
                            var layer = layui.layer;
                            var form = layui.form;

                            // 创建模态框内容
                            var modalContent = createModalContent(existingData);

                            // 使用 layer.open 显示模态框
                            layer.open({
                                type: 1,
                                title: '编辑物料',
                                area: '500px',
                                content: modalContent,
                                success: function (layero, index) {
                                    form.render(); // 渲染表单组件
                                }
                            });
                        });
                    }


 






                    // 监听编辑按钮点击事件
                    form.on('submit(edit)', function (data) {
                        console.log(data);
                        $.ajax({
                            url: "/Wyx/EditProduct",
                            type: "GET",
                            data: {
                                input: JSON.stringify(data.field),
                            },
                            dataType: "json",
                            success: function (res) {
                                console.log(res);
                                layer.msg('编辑成功', {
                                    icon: 1,
                                    time: 1000
                                });
                            }
                        });
                    });
                });
            };

=======
                 
>>>>>>> 64db4f2d35c44b2a82e33fef505e1219a974fb8b

          
         


           


          
        });

        






       
    </script>
</body>
</html>
